http = require("http");
querystring = require("querystring");
url = require("url");


function start(route, handle){
	function start_on_request(req, res){
		var pathname = url.parse(req.url).pathname;
		var postdata = "";
		console.log("Request Received!");
		req.setEncoding("utf8");
		req.addListener("data", function(postdata_t){
			postdata += postdata_t;
			console.log("Good, one more data\t" + postdata_t );
		})
		req.addListener("end", function(){
			route(handle, pathname, res, postdata);
		})
	}
	http.createServer(start_on_request).listen(8888);
	console.log("Server Has Started.");
}

function responseTEXT(response, words){
	response.writeHead(200, {"Content-type":"text/plain"});
	response.write(words);
	response.end();
}

function responseHTML(response, html_doc){
	response.writeHead(200, {"Content-type":"text/html"});
	response.write(html_doc);
	response.end();
}

function route(handle, pathname, res, postdata_t){
	console.log("About to route a request for " + pathname);
	if (typeof handle[pathname] == 'function'){
		handle[pathname](res, postdata_t);
	} else {
		console.log(typeof handle[pathname]);
		console.log("No Request handler found for " + pathname);
	}
}


function res_start(res, postdata_t){
	console.log("Request handler 'start' was called.");
	responseTEXT(res, "Hello World.");
}

function res_upload(res, postdata_t){
	console.log("Request handler 'upload' was called.");
	responseTEXT(res, "You've sent "+querystring.parse(postdata_t).text);
}

function res_webpage(res, postdata_t){
	console.log("Request.");
	var body = '<html>'+    '<head>'+    '<meta http-equiv="Content-Type" content="text/html; '+    'charset=UTF-8" />'+    '</head>'+    '<body>'+    '<form action="/upload" method="post">'+    '<textarea name="text" rows="20" cols="60"></textarea>'+    '<input type="submit" value="Submit text" />'+    '</form>'+    '</body>'+    '</html>'; 
	responseHTML(res, body);
}

var handIns = {};
handIns["/start"] = res_start;
handIns["/upload"] = res_upload;
handIns["/webpage"] = res_webpage;

start(route, handIns);




